#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'


import collections
import maya.cmds as cmds
import yaml
import os


class VerAbcExport(object):
    def __init__(self, filePath, config='abc_config.yml'):
        """
        exporter = VerAbcExport(filePath="x:/xx/xx.abc", config='abc_config.yml')
        exporter.exportObjects = nodesList
        exporter.frameRange = (1,100)
        exporter.main()
        """
        self._optionsList = []
        self._frameRange = []
        self.exportObjects = None
        self.outPath = filePath
        self.validatePath(self.outPath)
        self._config = config
        if not cmds.pluginInfo("AbcExport.mll", q=1, l=1):
            cmds.loadPlugin( "AbcExport.mll")

    @staticmethod
    def validatePath(filePath):
        if not os.path.isdir(os.path.dirname(filePath)):
            os.makedirs(os.path.dirname(filePath))
            
    def _initData(self):
        configFile = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config', self._config)
        #configFile = 'D:/apps/verexport/config/abc_config.yml'
        if not os.path.isfile(configFile):
            raise RuntimeError("config file not exists: %s \n" % configFile)
        data = self.getConfigData(configFile)
        optionsData = data.get('options', None)
        if not optionsData:
            raise RuntimeError("config error.")
        self._setOption(optionsData)
        attrsData = data.get('attrs', None)
        if attrsData:
            self.addAttrs(attrsData)
        
    @staticmethod
    def getConfigData(configFile):
        data = None
        with open(configFile) as f:
            data = yaml.load(f)
        if data:
            return data
            
    def _setOption(self, data):
        for attr, value in data.iteritems():
            if isinstance(value, str):
                self._optionsList.append('{attr} "{value}" '.format(attr=attr, value=value))
            elif isinstance(value, bool):
                if value:
                    self._optionsList.append('{attr} '.format(attr=attr))
            else:
                self._optionsList.append('{attr} {value} '.format(attr=attr, value=value))
        self._optionsList.append('file {value} '.format(value=self.outPath))
            
    def _setObject(self):
        if self.exportObjects:
            for obj in self.exportObjects:
                self._optionsList.append("root {} ".format(obj))
                
    def _setFrameRange(self):
        if self._frameRange:
            self._optionsList.append('frameRange {} {} '.format(*self._frameRange))
    
    def addAttrs(self, data):
        for attr in data:
            self._optionsList.append("attr {} ".format(attr))
            
    @property
    def frameRange(self):
        return self._frameRange

    @frameRange.setter
    def frameRange(self, value):
        if isinstance(value, collections.Iterable):
            self._frameRange = list(value)
        else:
            raise TypeError("Value should be an iterable.")
            
    def main(self):
        self._initData()
        if not self.exportObjects:
            raise RuntimeError("Please set exportObjects.")
        self._setObject()
        self._setFrameRange()
        jString = '-'+'-'.join(self._optionsList)
        cmds.AbcExport(j=jString)
        return self.outPath


        